<?php
/**
 * @package		mod_qlform
 * @copyright	Copyright (C) 2012 ql.de All rights reserved.
 * @author 		Mareike Riegel mareike.riegel@ql.de
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

jimport( 'joomla.form.form' );

$arr_files=array("modelQlForm","modelQlCaptcha","modelQlCaptcha","modelQlMailer","modelQlDatabase","modelQlMessager","modelQlSomethingElse");
foreach ($arr_files as $k=>$v) if (!class_exists($v) AND file_exists($file=dirname(__FILE__).'/classes/'.$v.'.php')) require_once($file);

class modQlFormHelper
{

	/**
	 * method to do something else, 
	 * that the developer of this module could never have guessed 
	 * 
	 * @param mixed $variable at your service 
	 */  
    function doSomethingElse($data,$params)
    {
       $obj=new modelQlSomethingElse($data,$params);
       if (1==$obj->doSomethingElse()) $this->arrMessages[]=array("warning"=>0, "str"=>JTEXT::_('MOD_QLFORM_SOMETHINGELSEWORKEDOUTFINE'));
       else $this->arrMessages[]=array("warning"=>1, "str"=>JTEXT::_('MOD_QLFORM_SOMETHINGELSEDIDNOTWORK'));
    }
	
	/**
	 * method to transform string with [ and ] to xml with < and >
	 *
	 * @param string $str_content of param cell
	 * @return string $str_xml
	 */
    function transformText($str_content)
    {
        $str_xml=$str_content;
    	$str_xml=preg_replace("/\[/","<",$str_xml);
        $str_xml=preg_replace("/\]/",">",$str_xml);
        return $str_xml;
    }
	/**
	 * method to generate an array for a field
	 *
	 * @param string $field field name
	 * @param string $type type of field
	 * @param string $label of field, if empty gets value or fieldname 
	 * @return string 
	 */
    
    function generateArrayField($field,$type,$label="",$value=false)
    {
		$arr=array();
    	$arr['name']=$field;
		$arr['type']=$type;
		$arr['label']=$label;
		if ("user_id"==$field) $arr['value']=$this->getUserData('id');
		elseif ("user_email"==$field) $arr['value']=$this->getUserData('email');
		elseif ("article_id"==$field) $arr['value']=$this->getArticleData('id');
		elseif ("article_title"==$field) $arr['value']=$this->getArticleData('title');
		else $arr['value']=$value;
		$this->arrFields[]=$arr;
    }
	/**
	 * method to add field to xml
	 *
	 * @param string $str_xml
	 * @param string $arrFields array of fields to add
	 * @return string $str_xml
	 */
    function addFieldsToXml($str_xml,$arrFields)
    {
        if (is_array($arrFields))
        {
	    	$formCloseTag="</form>";
	    	$str_xml=str_replace($formCloseTag, "<fieldset name='qlform".md5(rand(0,100))."'>".$formCloseTag,$str_xml);
	    	foreach ($arrFields as $k=>$v)
	        {
	        	$str_fieldtag='<field name="'.$v['name'].'" default="'.$v['value'].'" type="'.$v['type'].'" label="'.$v['label'].'" />';
	        	$str_xml=str_replace($formCloseTag, $str_fieldtag.$formCloseTag,$str_xml);
	        	$str_tag="";
	        }
	        $str_xml=str_replace($formCloseTag, "</fieldset>".$formCloseTag,$str_xml);
        }
        return $str_xml;
    }
    /**
     * method to get fields from current article
     * @param string $field
     * @return result field value
     * see http://forum.joomla.org/viewtopic.php?t=525350
     */
    function getArticleData($field)
    {
    	$option = JRequest::getCmd('option');
    	$view = JRequest::getCmd('view');
    	if ($option=="com_content" && $view=="article") 
    	{
    		$ids = explode(':',JRequest::getString('id'));
    		$article_id = $ids[0];
    		$article =& JTable::getInstance("content");
    		$article->load($article_id);
    		return $article->get($field);
    	}
    	else return false;
    }

    /**
     * method to get fields from current user
     * @param string $field
     * @return result field value
     */
    function getUserData($field)
    {
    	$user =& JFactory::getUser();
    	if (""!=$user->get($field)) return $user->get($field);
    	else return false;
    }
    
    /** 
     * method to transform xml string to xml object 
     * @param string $str_xml
     * @return object xml
     */
    function getXml($str_xml)
    {
        return simplexml_load_string($str_xml); 
    }
	/**
	 * Method to get the form based on str_xml.
	 *
	 * The base form is loaded from XML and then an event is fired
	 * for users plugins to extend the form with extra fields.
	 *
	 * @param	array	$str_xml		An optional array of data for the form to interogate.
	 * @return	mixed  	$form		JForm object on success, false on failure
	 * @since	1.6
	 */
    public function getForm($str_xml)
	{
		$this->obj_form=new modelQlForm();
		$this->obj_form->form_name="qlform";
		$this->obj_form->str_xml=$str_xml;
		$form=$this->obj_form->getForm();
		if (is_object($form)) return $form; 
		else $this->arrMessages[]=array("warning"=>1, "str"=>JTEXT::_('MOD_QLFORM_NO_FORM_GIVEN'));
		return false;
	}

	/**
	 * Method to get the form based on str_xml.
	 *
	 * The base form is loaded from XML and then an event is fired
	 * for users plugins to extend the form with extra fields.
	 *
	 * @param	array	$data		An array of data (post data) to be validated
	 * @return	mixed  	$form		JForm object on success, false on failure
	 * @since	1.6
	 */
    public function validate($data)
	{
		$validated=$this->obj_form->check($data);
		if (0==$validated) $this->arrMessages[]=array("warning"=>1,"str"=>JTEXT::_('MOD_QLFORM_VALIDATION_FAILED'));
		$this->raiseError();
		return $validated;
	}

	/**
	 * Method to raise Errors
	 *
	 * @param	int	$type		type of error displayed, either via joomla or text displayes
	 * @since	1.6
	 */
    public function raiseError()
	{
		if (isset($this->obj_form->formErrors) AND is_array($this->obj_form->formErrors)) 
		foreach ($this->obj_form->formErrors as $k=>$v) $this->arrMessages[]=array("warning"=>1, "str"=>$v->get('message'));
	}

	/**
	 * Method to raise Errors
	 *
	 * @param	int	$type		type of error displayed, either via joomla or text displayes
	 * @since	1.6
	 */
    public function displayMessages($type)
    {
		$obj_messager = new modelQlMessager($this->arrMessages,$type);
		if (isset($obj_messager->message) AND !empty($obj_messager->message)) return $obj_messager->message; 
	}
	/**
	 * Method for checking database     
	 *
	 * @param   string  $table      Name of table to save data in
	 * @param   array  	$data 		Array of data to compare to tabel cols
	 *
	 * @return  mixed 	array with table cols on success, false on failure
	 *
	 */	
	public function connectToDatabase()
	{
		$this->obj_database=new modelQlDatabase();
	}
	/**
	 * Method for saving data in database  
	 *
	 * @param   string  $database  database name 
	 * @param   string  $table      Name of table to save data in
	 * @param   bool  	$showErrors If to raise Errors or let be
	 *
	 * @return  bool 	true on success, false on failure
	 *
	 */	
	public function saveToDatabase($table,$data,$showErrors)
	{
		$data=array_intersect_key($data,$this->arrTableFields);
		$this->obj_database->save($table,$data);
		return true;
	}
	/**
	 * Method for checking database     
	 *
	 * @param   string  $table      Name of table to save data in
	 * @param   array  	$data 		Array of data to compare to tabel cols
	 *
	 * @return  mixed 	array with table cols on success, false on failure
	 *
	 */	
	public function checkDatabase($table,$str_xml,$showErrors,$fieldCreated)
	{
		$checkTable=$this->checkTableExists($table,$showErrors);
		$this->compareTableToData($this->arrTableFields,$str_xml,$showErrors,$table,$fieldCreated);
		return $checkTable;
	}
	/**
	 * Method for checking if table exists    
	 *
	 * @param   string  $table      Name of table to save data in
	 * @param   bool  	$showErrors If to raise Errors or let be
	 * 
	 * @return  bool 	truewith table cols on success, false on failure
	 *
	 */	
	public function checkTableExists($table,$showErrors)
	{
		$strDatabase=$this->obj_database->getJDatabase();
		$table=$this->obj_database->jGetTable($table);

		$tableExists=$this->obj_database->tableExists($strDatabase,$table);
		$this->arrTableFields=array();
		if (false==$tableExists AND 1==$showErrors) 
		{
			$this->arrMessages[]=array("warning"=>1, "str"=>sprintf(JText::_('MOD_QLFORM_DBNOTFOUND_FORM'),$table,$strDatabase));
			return false;
		}
		$arrDatabase=$this->obj_database->getDatabaseFields($strDatabase,$table);
		$this->arrTableFields=$this->obj_database->databaseFieldsObjectToArray($arrDatabase);
		return true;
	}
	/**
	 * Method for checking if table exists    
	 *
	 * @param   string  $table      Name of table to save data in
	 * @param   bool  	$showErrors If to raise Errors or let be
	 *
	 * @return  bool 	true on success, false on failure
	 *
	 */	
	public function compareTableToData($arrTableFields,$str_xml,$showErrors,$table,$fieldCreated)
	{
		$xml=$this->getXML($str_xml);
		$arrFormFields=array_flip($this->getFields($xml));
		if (1==$fieldCreated)$arrFormFields['created']=0;
		$arrDifference1=array_diff_key($arrFormFields,$arrTableFields);
		$arrDifference2=array_diff_key($arrTableFields,$arrFormFields);
		$this->arrClean=array_intersect_key ($arrFormFields,$arrTableFields);
		if (1==$showErrors)
		{ 
			if (1<=count($arrDifference1) OR 1<=count($arrDifference2)) $this->arrMessages[]=array("warning"=>1, "str"=>JText::_('MOD_QLFORM_DBFORM_ERROR_TITLE'));
			foreach ($arrDifference1 as $k=>$v) $this->arrMessages[]=array("warning"=>1, "str"=>sprintf(JText::_('MOD_QLFORM_DBFORM_ERROR_DATABASE'),$k,$table));
			foreach ($arrDifference2 as $k=>$v) $this->arrMessages[]=array("warning"=>1, "str"=>sprintf(JText::_('MOD_QLFORM_DBFORM_ERROR_FORM'),$k,$table));
			if (1<=count($arrDifference1) OR 1<=count($arrDifference2)) $this->arrMessages[]=array("warning"=>1, "str"=>JText::_('MOD_QLFORM_DBFORM_ERROR_GENERAL'));
		}
		return true;
	}
	
	/**
	 * Method for checking database     
	 *
	 * @param   string  $table      Name of table to save data in
	 * @param   array  	$data 		Array of data to compare to tabel cols
	 *
	 * @return  mixed 	array with table cols on success, false on failure
	 *
	 */	
	public function getFields($xml)
	{
		//print_r($xml);die;
		if (is_object($xml->fieldset)) foreach ($xml->fieldset as $k=>$v)
		{
			if (is_object($v->field)) foreach ($v->field as $k2=>$v2)
			{
				if (isset($v2['type']) AND "spacer"!=$v2['type']) $arr[]=(string) $v2['name'];
			}
		}
		return $arr;
	}
	/**
	 * Method to mail
	 *
	 * @param	string	$recipient email address of recipient
	 * @param	string	$subject of email
	 * @param 	array   $data array of post data to be sent
	 * @since	1.6
	 */	
	public function mail($recipient,$subject,$data)
	{
		$obj_mailer=new modelQlMailer();
		$mailSent=$obj_mailer->mail($recipient,$subject,$data);
		if (1==$mailSent) 
		{
			$this->arrMessages[]=array("str"=>JText::_('MOD_QLFORM_MAIL_SENT'));
			return true;	
		}
		else 
		{
			$this->arrMessages[]=array("warning"=>1, "str"=>JText::_('MOD_QLFORM_MAIL_SENT_ERROR'));
			return false;
		}
	}
	
	/**
	 * Method to initiate captcha
	 *
	 * @param	int	$type		type of error displayed, either via joomla or text displayes
	 * @since	1.6
	 */	
	public function initiateCaptcha()
	{
		$obj_captcha=new modelQlCaptcha("modules/mod_qlform/captcha/fonts/LEXIB___.ttf","tmp");
		$obj_captcha->intTextLenght=4;
		$obj_captcha->intFontSize=26;
		$obj_captcha->intIMGWidth=140;
		$obj_captcha->intIMGHeight=60;
		$obj_captcha->arrBG=array(255,255,255);
		$obj_captcha->arrTxt=array(24,24,24);
		$this->obj_captcha=$obj_captcha;
	}
	/**
	 * Method to generate captcha
	 *
	 * @param	int	$type		type of error displayed, either via joomla or text displayes
	 * @since	1.6
	 */	
	public function generateCaptcha()
	{
		$this->captcha=$this->obj_captcha->getFilename();
		$this->obj_captcha->generateCaptcha();
		$this->obj_captcha->setSession();
	}
	/**
	 * Method to check captcha
	 *
	 * @param	int	$type		type of error displayed, either via joomla or text displayes
	 * @since	1.6
	 */	
	public function checkCaptcha($strCaptcha,$data)	
	{
		$validated=$this->obj_captcha->checkCaptcha($strCaptcha);
		if (0==$validated) $this->arrMessages[]=array("warning"=>1,"str"=>JTEXT::_('MOD_QLFORM_CAPTCHA_FAILED'));
		return $validated;
	}

	/**
	 * method to merge two subarray given 
	 * 
	 * @param array $array multidimensional array 
	 * @param string $index1 index of subarray to be merged
	 * @param string $index2 index of second subarray to be merged
	 * @return mixed $mergedArray array containing elements of former subarray on success, false on failure
	 */  
	function mergeSubarrays($array,$index1,$index2)
	{
		if (isset($array[$index1]) AND is_array($array[$index1]) AND isset($array[$index2]) AND is_array($array[$index2])) $mergedArray=array_merge($array[$index1],$array[$index2]);
		else if (isset($array[$index1]) AND is_array($array[$index1])) $mergedArray=$array[$index1];
		else if (isset($array[$index2]) AND is_array($array[$index2])) $mergedArray=$array[$index2];
		else return false;
		return $mergedArray;
	}
}